package action;

import inc.CommonFunction;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lottery.BankAccountConfig;
import lottery.BankDeposit;
import lottery.BetwayManage;
import lottery.ClientVersion;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.hibernate.Session;

import code.lewdy.app.communication.Alert;
import code.lewdy.app.notice.Notice;
import code.lewdy.app.user.AccountRecord;
import code.lewdy.app.user.WithdrawRecord;
import code.lewdy.db.HibernateTemple;
import code.lewdy.db.JdbcTemple;
import code.lewdy.time.TimeHelper;
import code.lewdy.web.response.ExtResponse;

import com.lt.member.Member;
import com.lt.member.MemberConfig;
import com.opensymphony.xwork2.ActionSupport;

import dao.HibernateSessionFactory;

/**
 * 数据更新 Flex传对象参数: var params:Object = new Object(); params["m.username"] =
 * "我的中"; http.send(params);
 * 
 * @author liuding,2012-5-16
 * 
 *         $LastChangedDate$ $Author$
 */
public class UpdateAction extends ActionSupport implements ServletResponseAware,ServletRequestAware {

	private CommonFunction fun = new CommonFunction();
	private String ext1; // 扩展参数
	private String ext2;
	private HttpServletResponse resp;
	private HttpServletRequest req;
	private String classPath;
	private BetwayManage betwayMg;
	private Notice notice;
	private Member member;
	private BankDeposit bankdp;
	private AccountRecord ar;
	private BankAccountConfig rechargeBank;
	private WithdrawRecord withdraw;
	private MemberConfig mcfg;
	
	public String updateBySQL(){
		String sql = ext1;
		JdbcTemple.executeUpdate(sql);
		return null;
	}
	
	//版本更新
	public String v(){
		String appName = ClientVersion.getProperty(ClientVersion.APP_NAME);
		String version = ClientVersion.getProperty(ClientVersion.VERSION);
		String site = ClientVersion.getProperty(ClientVersion.SITE);
		String ext = ClientVersion.getProperty(ClientVersion.EXT);
		String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath()+"/";
		url += "client/" + appName + version + "_" + site + "." + ext;
		String text = "<resp><version>"+version+"</version>"
			+ "<site>"+site+"</site> "
			+ "<ext>"+ext+"</ext> "
			+ "<url>"+url+"</url></resp>";
		ExtResponse.outString(resp, text, "xml");
		return null;
	}
	
	/**
	 * 更新数据
	 * 
	 * @return
	 */
	public String update() {
		if (ClassName.CLASS_BETWAYMANAGE.equals(classPath)) {
			if (betwayMg == null) {
				System.out.println("update=>BetwayManage is NULL");
				return null;
			}
			BetwayManage bm = (BetwayManage) HibernateTemple.load(
					BetwayManage.class, betwayMg.getId());
			bm.setReturnPoint(betwayMg.getReturnPoint());
			bm.setReward(betwayMg.getReward());
			bm.setMaxFrontReturnPoint(betwayMg.getMaxFrontReturnPoint());
			bm.setTopReturnDistance(betwayMg.getTopReturnDistance());
			bm.setIsAdjustable(betwayMg.getIsAdjustable());
			HibernateTemple.update(bm);
		} else if (Notice.class.getName().equals(classPath)) {
			Notice n = (Notice) HibernateTemple.load(Notice.class, notice
					.getId());
			n.setContent(notice.getContent());
			n.setTitle(notice.getTitle());
			HibernateTemple.update(n);
		} else if (BankDeposit.class.getName().equals(classPath)) {
			BankDeposit bd = (BankDeposit) HibernateTemple.load(
					BankDeposit.class, bankdp.getId());
			bd.setBankName(bankdp.getBankName());
			HibernateTemple.update(bd);
		} else if (BankAccountConfig.class.getName().equals(classPath)) {
			if (rechargeBank == null) {
				System.out.println("update=>BankAccountConfig is NULL!");
				return null;
			}
			BankAccountConfig bank = (BankAccountConfig) HibernateTemple.load(
					BankAccountConfig.class, rechargeBank.getId());
			bank.setAccountName(rechargeBank.getAccountName());
			bank.setBankName(rechargeBank.getBankName());
			bank.setCardNo(rechargeBank.getCardNo());
			bank.setNote(rechargeBank.getNote());
			bank.setMail(rechargeBank.getMail());
			HibernateTemple.update(bank);
		}else if(WithdrawRecord.class.getName().equals(classPath)){
			if(withdraw==null){
				System.out.println("update=>WithdrawRecord is NULL!");
				return null;
			}
			WithdrawRecord wr = (WithdrawRecord) HibernateTemple.load(WithdrawRecord.class, withdraw.getId());
			wr.setStatus(withdraw.getStatus());
			wr.setHandleDate(new Date());
			Member m = (Member) HibernateTemple.load(Member.class, Integer.parseInt(""+wr.getOwnerId()));
			HibernateTemple.update(wr);
			new Alert().save(m, "提现成功", "您提现"+wr.getAmount()+"元已处理，请查收!");
		}else if(MemberConfig.class.getName().equals(classPath)){
			MemberConfig mcfg2 = (MemberConfig) HibernateTemple.load(MemberConfig.class, mcfg.getId());
			if(mcfg2==null){
				//不存在插入
				mcfg2.setDepositBeginTime(TimeHelper.getSecondsByTime(ext1));
				mcfg2.setDepositEndTime(TimeHelper.getSecondsByTime(ext2));
				HibernateTemple.save(mcfg);
			}else{
				//存在则更新
				mcfg2.setMaxFrontReturnPoint(mcfg.getMaxFrontReturnPoint());
			//	mcfg2.setReturnPointBase(mcfg.getReturnPointBase());
				mcfg2.setTopReturnDistance(mcfg.getTopReturnDistance());
				mcfg2.setDepositBeginTime(TimeHelper.getSecondsByTime(ext1));
				mcfg2.setDepositEndTime(TimeHelper.getSecondsByTime(ext2));
				mcfg2.setDepositMaxCount(mcfg.getDepositMaxCount());
				mcfg2.setDepositMinAmount(mcfg.getDepositMinAmount());
				mcfg2.setDepositMaxAmount(mcfg.getDepositMaxAmount());
				HibernateTemple.update(mcfg2);
			}
		}
		return null;
	}

	/**
	 * 更改用户的基本信息
	 * 
	 * @return
	 */
	public String updateBasicInfo() {
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		Member m = (Member) s.get(Member.class, member.getId());
		s.getTransaction().commit();
		m.setIsLock(member.getIsLock());
		m.setAccountType(member.getAccountType());
		m.setReturnPoint(member.getReturnPoint());
		m.setBdReturnPoint(member.getBdReturnPoint());
		// 如果密码改变了就加密并更新
		if(!m.getPassword().equals(member.getPassword())){
			m.setPassword(fun.encryptPassword(member.getPassword()));
		}
		s.beginTransaction();
		s.update(m);
		s.getTransaction().commit();
		s.close();
		return null;
	}

	/**
	 * 更改用户的银行账户信息
	 * 
	 * @return
	 */
	public String updateBankInfo() {
		if (member == null) {
			System.out.println("UpdateAction.updateBankInfo()=>member is NULL");
			return null;
		}
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		Member m = (Member) s.get(Member.class, member.getId());
		s.getTransaction().commit();
		m.setBankName(member.getBankName() != null ? member.getBankName() : m
				.getBankName());
		m.setBankNo(member.getBankNo());
		m.setBankAccountName(member.getBankAccountName());
		// 如果密码改变了就加密并更新
		if(!m.getSecurityPassword().equals(member.getSecurityPassword())){
			m.setSecurityPassword(fun.encryptPassword(member.getSecurityPassword()));
		}
		s.beginTransaction();
		s.update(m);
		s.getTransaction().commit();
		s.close();
		return null;
	}

	/**
	 * 为下级充值
	 * 
	 * @return
	 */
	public String rechargeForLower() {
		if (ar == null) {
			System.out
					.println("UpdateAction.rechargeForLower()=>AccountRecord is NULL!");
		}
		ar.setAmountOut(ar.getAmountOut()>0 ? ar.getAmountOut() : -ar.getAmountOut());
		int topId = Integer.parseInt(""+ar.getOwnerId());
		// 验证资金密码
		Member m = (Member) HibernateTemple.load(Member.class, topId);
		if (m.getSecurityPassword() != null) {
			if (!m.getSecurityPassword().equals(fun.encryptPassword(ext1))) {
				ExtResponse.error(resp, "资金密码错误！", "xml");
				return null;
			}
		} else {
			ExtResponse.error(resp, "请先设置资金密码！", "xml");
			return null;
		}
		Date date = new Date();
		
		// 上级
		Member top = (Member) HibernateTemple.load(Member.class, Integer.parseInt(ar
				.getOwnerId()
				+ ""));
		//下级
		Member low = (Member) HibernateTemple.load(Member.class, Integer
				.parseInt(ar.getExt1()));
		double rechargeAmount = ar.getAmountOut()>0 ? ar.getAmountOut() : -ar.getAmountOut();
		top.setBalance(top.getBalance() - rechargeAmount);
		low.setBalance(low.getBalance() + rechargeAmount);

		HibernateTemple.update(top);
		HibernateTemple.update(low);
		ar.setCreateDate(date);
		ar.setType(AccountRecord.EXPENDITURE);
		ar.setGroupId(AccountRecord.GROUP_USER_WITHDRAW);
		ar.setNote("为下级充值");
		ar.setBalance(top.getBalance());
		if(ar.getAmountOut() > 0){
			ar.setAmountOut(-ar.getAmountOut());
		}
		AccountRecord ar2 = new AccountRecord();
		ar2.setAmountIn(rechargeAmount);
		ar2.setAttachName("上级帮助充值");
		ar2.setCreateDate(date);
		ar2.setExt1(ar.getOwnerId() + "");
		ar2.setOwnerId(Long.parseLong(ar.getExt1()));
		ar2.setOwnerName(ar.getExt2());
		ar2.setNote("上级帮助充值");
		ar2.setType(AccountRecord.INCOME);
		ar2.setGroupId(AccountRecord.GROUP_RECHARGE_BY_OTHER);
		ar2.setBalance(low.getBalance());
		HibernateTemple.save(ar);
		HibernateTemple.save(ar2);
		//更新提示信息
		new Alert().save(top, "为下级充值成功", "您为下级"+low.getUsername()+"充值"+ar.getAmountOut()+"元充值成功！请核对，订单号"+ar.getOrderId());
		new Alert().save(low, "充值成功", "您上级"+top.getUsername()+"为您充值"+rechargeAmount+"元已到账！请查收，订单号"+ar.getOrderId());
		ExtResponse.ok(resp, "为下级充值成功！", "xml");
		return null;
	}

	/**
	 * 更新用户账户资金
	 * 
	 * @return
	 */
	public String updateAmount() {
		if (member == null) {
			System.out.println("UpdateAction.updateAmount()=>member is NULL");
			return null;
		}
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		Member m = (Member) s.get(Member.class, member.getId());
		s.getTransaction().commit();
		m.setBalance(member.getBalance());
		m.setTotalAmount(member.getTotalAmount());
		m.setFreezeAmount(member.getFreezeAmount());
		s.beginTransaction();
		s.update(m);
		s.getTransaction().commit();
		s.close();
		return null;
	}

	public static void main(String[] args) {
		System.out.println(Notice.class.getName());
	}

	public BetwayManage getBetwayMg() {
		return betwayMg;
	}

	public void setBetwayMg(BetwayManage betwayMg) {
		this.betwayMg = betwayMg;
	}

	public void setClassPath(String classPath) {
		this.classPath = classPath;
	}

	public String getClassPath() {
		return classPath;
	}

	public Notice getNotice() {
		return notice;
	}

	public void setNotice(Notice notice) {
		this.notice = notice;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public void setBankdp(BankDeposit bankdp) {
		this.bankdp = bankdp;
	}

	public BankDeposit getBankdp() {
		return bankdp;
	}

	public void setAr(AccountRecord ar) {
		this.ar = ar;
	}

	public AccountRecord getAr() {
		return ar;
	}

	public void setExt1(String ext1) {
		this.ext1 = ext1;
	}

	public String getExt1() {
		return ext1;
	}

	public void setServletResponse(HttpServletResponse resp) {
		// TODO Auto-generated method stub
		this.resp = resp;
	}

	public void setRechargeBank(BankAccountConfig rechargeBank) {
		this.rechargeBank = rechargeBank;
	}

	public BankAccountConfig getRechargeBank() {
		return rechargeBank;
	}

	public void setWithdraw(WithdrawRecord withdraw) {
		this.withdraw = withdraw;
	}

	public WithdrawRecord getWithdraw() {
		return withdraw;
	}

	public void setMcfg(MemberConfig mcfg) {
		this.mcfg = mcfg;
	}

	public MemberConfig getMcfg() {
		return mcfg;
	}

	public void setExt2(String ext2) {
		this.ext2 = ext2;
	}

	public String getExt2() {
		return ext2;
	}

	public void setServletRequest(HttpServletRequest req) {
		// TODO Auto-generated method stub
		this.req = req;
	}

}
